import { createI18n } from 'vue-i18n'

export type LangType = 'zh-cn' | 'en' | 'vi'
// 默认的语言
export const defaultLang = 'en'

const i18n = createI18n({
  locale: defaultLang,
  fallbackLocale: defaultLang,
  silentFallbackWarn: true,
  silentTranslationWarn: true,
  globalInjection: true,
  allowComposition: true,
})
// 变更语言
export const changeLang = (lang: LangType) => {
  localStorage.setItem('lang_active', lang)
  loadLanguageAsync(lang)
}
// 设置当前的语言
export const setI18nLanguage = (lang: LangType) => {
  i18n.global.locale = lang
  return lang
}
// 动态获取当前的语言
export const loadLanguageAsync = async (lang: LangType) => {
  return import(/* @vite-ignore */ `./${lang}.ts`)
    .then(msgs => {
      i18n.global.setLocaleMessage(lang, msgs.default)
      return setI18nLanguage(lang)
    })
    .catch(console.error)
}

changeLang(defaultLang)

export default i18n
